<?php

namespace houze;

/*
* 分布式操作类
*/

class Distributed{
    
    // 单例
    private static $instance = null;
    
    // 单例方法
    public static function run(){
        if(empty(self::$instance)) self::$instance = new Distributed();
        return self::$instance;
    }
    
    // mysql读写分离节点最佳选择
    public function mysql($type='write'){
        // 获取配置信息
        $config = \houze\Config::get('mysql');
        // 默认连接配置信息
        $pool_list = $config['pool_list'];
        // 是否开启读写分离
        if($config['is_proxy'] == false) return new \houze\Db($pool_list['default']);
        // 开始读写分离
        $proxy = $config['proxy'];
        // 判断节点是否存在，否则返回默认节点
        if(count($proxy['write']) == 0) return new \houze\Db($pool_list['default']);
        if(count($proxy['read']) == 0) return new \houze\Db($pool_list['default']);
        // 临时存储连接数
        $max_arr = [];
        // 临时存储数据库配置
        $cache_arr = [];
        if($type == 'write'){
            foreach ($proxy['write'] as $k => $v){
              $max_result = $this->mysqlMaxConnect($v, $max_arr, $cache_arr);
              $max_arr = $max_result['max'];
              $cache_arr = $max_result['cache'];
            }
        }else {
            foreach ($proxy['read'] as $k => $v) {
              $max_result = $this->mysqlMaxConnect($v, $max_arr, $cache_arr);
              $max_arr = $max_result['max'];
              $cache_arr = $max_result['cache'];
            }
        }
        
        // 获取最优连接对象
        return new \houze\Db($cache_arr[max($max_arr)]);
    }
    
    // mysql负载最优判断
    public function mysqlMaxConnect($config, $max_arr, $cache_arr){
        $Db = new \houze\Db($config);
        // 连接数
        $mysql_connect_num = $Db->query("show status like 'Threads%'")[1];
        $cache_arr[$mysql_connect_num['Value']] = $config;
        array_push($max_arr, intval($mysql_connect_num['Value']));
        $Db->return();
        
        return ['max'=>$max_arr, 'cache'=>$cache_arr];
    }
}